/*
 * @Author: peng.chen2 peng.chen2@rt-mart.com
 * @Date: 2025-07-26 10:00:00
 * @LastEditors: peng.chen2
 * @LastEditTime: 2025-08-01 09:23:27
 * @FilePath: /rt-monitoring/src/contexts/ThemeContext.tsx
 * @Description: 主题切换上下文
 */

import React, { createContext, useContext, useState, useEffect } from 'react'
import { ConfigProvider } from 'antd'
import { darkTheme, lightTheme } from '../config/antd'
import type { ThemeConfig } from 'antd'

interface ThemeContextType {
  isDark: boolean
  toggleTheme: () => void
  currentTheme: ThemeConfig
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined)

interface ThemeProviderProps {
  children: React.ReactNode
}

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  const [isDark, setIsDark] = useState(() => {
    // 从 localStorage 读取主题设置，默认为暗色主题
    const savedTheme = localStorage.getItem('theme-mode')
    return savedTheme ? savedTheme === 'dark' : true
  })

  const toggleTheme = () => {
    setIsDark(prev => {
      const newTheme = !prev
      localStorage.setItem('theme-mode', newTheme ? 'dark' : 'light')
      return newTheme
    })
  }

  const currentTheme = isDark ? darkTheme : lightTheme

  // 监听系统主题变化
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleChange = (e: MediaQueryListEvent) => {
      // 只有在用户没有手动设置主题时才跟随系统
      const savedTheme = localStorage.getItem('theme-mode')
      if (!savedTheme) {
        setIsDark(e.matches)
      }
    }

    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [])

  // 更新 CSS 变量以支持全局主题
  useEffect(() => {
    const root = document.documentElement
    if (isDark) {
      root.setAttribute('data-theme', 'dark')
    } else {
      root.setAttribute('data-theme', 'light')
    }
  }, [isDark])

  const value: ThemeContextType = {
    isDark,
    toggleTheme,
    currentTheme,
  }

  return (
    <ThemeContext.Provider value={value}>
      <ConfigProvider theme={currentTheme}>{children}</ConfigProvider>
    </ThemeContext.Provider>
  )
}

export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext)
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider')
  }
  return context
}

export default ThemeContext
